<template>
  <div>
    <Breadcrumb :style="{margin: '16px 0'}">
      <BreadcrumbItem>首页</BreadcrumbItem>
      <BreadcrumbItem to="/person">人员管理</BreadcrumbItem>
      <BreadcrumbItem>人员列表</BreadcrumbItem>
    </Breadcrumb>
    <Card>
      <div style="min-height: 600px">
        <Row>
          <Col span="8">
            <Tree :data="deptData" @on-select-change="checkChange" :render="personTreeRender"></Tree>
          </Col>
        </Row>
        <Row>
          <Col span="24">
            <Divider></Divider>
            <Button type="primary" size="large" to="/person/add" style="margin-bottom:20px;">添加人员</Button>
            <Table :data="personList" :columns="columns"></Table>
            <div style="margin-top:20px;">
              <Page :total="total" placement="top" show-sizer @on-page-size-change="pageSizeChange" @on-change="pageChange" />
            </div>
          </Col>
        </Row>
      </div>
    </Card>
    <Modal v-model="resetPwdModal">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>重置用户密码？</span>
      </p>
      <div style="text-align:center">
        <p>此操作将重置用户密码为“123456”。</p>
        <p>是否继续？</p>
      </div>
      <div slot="footer">
        <Button type="default" @click="resetPwdModal = false">取消</Button>
        <Button type="primary" @click="handleResetPwd">确定</Button>
      </div>
    </Modal>
    <Modal v-model="personModal">
      <p slot="header" style="text-align:left;font-size:18px;">
        <span>编辑人员</span>
      </p>
      <div>
        <Form v-model="personData">
          <FormItem label="姓名">
            <Input v-model="personData.name" placeholder="请输入要添加的人员姓名" disabled />
          </FormItem>
          <FormItem label="手机号">
            <Input v-model="personData.phone" placeholder="请输入手机号码" disabled />
          </FormItem>
          <FormItem label="所属角色">
            <Select v-model="personData.role" :label="personData.label">
              <Option v-for="role in roleList" :key="role.id" :value="role.id" :label="role.roleName"></Option>
            </Select>
          </FormItem>
          <FormItem label="状态">
            <Select v-model="personData.status">
              <Option v-for="item in statusList" :key="item.status" :value="item.status">{{item.name}}</Option>
            </Select>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button type="primary" @click="handleSubmitPerson()">确定</Button>
        <Button type="default" @click="personModal = false">取消</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import qs from 'qs'
export default {
  data() {
    return {
      pageno: 1,
      pageSize: 10,
      total: 0,
      deptId: '',
      resetPwdModal: false,
      personModal: false,
      personList: [],
      columns: [
        {
          title: '#',
          type: 'index'
        }, {
          title: '姓名',
          key: 'userName'
        }, {
          title: '角色',
          key: 'roleName'
        }, {
          title: '账号',
          key: 'account'
        }, {
          title: '操作',
          render: (h, param) => {
            return h('span', [
              h('Button', {
                props: {
                  type: 'primary',
                },
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.isEdit = true
                    this.personModal = true
                    this.personData = {
                      userId: param.row.id,
                      name: param.row.userName,
                      phone: param.row.account,
                      role: param.row.roleId,
                      label: param.row.roleName,
                      status: param.row.status
                    }
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'warning'
                },
                on: {
                  click: () => {
                    this.resetPwdModal = true
                    this.resetId = param.row.id
                  }
                }
              }, '重置密码')
            ])
          }
        }
      ],
      personData: {
        name: '',
        phone: '',
        role: '',
        status: '1',
        userId: '',
        label: ''
      },
      statusList: [
        {
          status: 1,
          name: '启用'
        }, {
          status: 3,
          name: '禁用'
        }
      ],
      resetId: '',
      roleList: [],
      deptData: [],
      classNow: -1
    }
  },
  methods: {
    checkChange(n, m) {
      console.log(n, m)
      this.deptId = n[0] ? n[0].id : ''
      this.pageno = 1
      this.$options.methods.getList(this)
    },
    pageSizeChange(n) {
      this.pageSize = n
      this.pageno = 1
      this.$options.methods.getList(this)
    },
    pageChange(n) {
      this.pageno = n
      this.$options.methods.getList(this)
    },
    getList(_this) {
      let url = '/bm/opera/sysuser/findSysuserPageList?pageNo=' + _this.pageno + '&pageSize=' + _this.pageSize

      if (_this.deptId != '') {
        url += ('&deptId=' + _this.deptId)
      }

      _this.$axios.get(url).then(res => {
        if (res.data.code == 200) {
          _this.personList = res.data.detail.list
          _this.pageSize = res.data.detail.pageSize
          _this.pageNo = res.data.detail.pageNum
          _this.total = res.data.detail.total
        }
      })
    },
    handleSubmitPerson(isedit) {
      if (this.isEdit) {
        this.$options.methods.editUser(this)
      } else {
        this.$options.methods.addUser(this)
      }
    },
    addUser(_this) {
      _this.$axios.post('/bm/opera/sysuser/addSysuser', qs.stringify({
        userName: _this.personData.name,
        account: _this.personData.phone,
        deptId: _this.personData.role
      })).then(res => {
        if (res.data.code == 200) {
          _this.$Message.success('人员信息更新成功！~')
          // this.$options.methods.getList(url, this)
        } else {
          _this.$Message.error(res.data.description)
        }
      })
    },
    editUser(_this) {
      _this.$axios.post('/bm/opera/sysuser/updateUser', qs.stringify({
        userId: _this.personData.userId,
        status: _this.personData.status,
        roleId: _this.personData.role
      })).then(res => {
        if (res.data.code == 200) {
          _this.personModal = false
          _this.$Message.success('人员信息更新成功！~')
          _this.$options.methods.getList(_this)
          // this.$options.methods.getList(url, this)
        } else {
          _this.$Message.error(res.data.description)
        }
      })
    },
    handleResetPwd() {
      this.$axios.post('/bm/opera/resetPassword', qs.stringify({
        userId: this.resetId
      })).then(res => {
        if (res.data.code == 200) {
          this.resetPwdModal = false
          this.$Message.success('用户密码已重置为“123456”')
        } else {
          this.$Message.error(res.data.description)
        }
      })
    },
    personTreeRender(h, {root, node, data}) {
      return h('span', {
        style: {
          display: 'inline-block',
          padding: '4px 8px',
          width: '100%',
          borderRadius: '3px',
          cursor: 'pointer'
        },
        class: {
          'selectttt': this.classNow == data.nodeKey
        },
        on: {
          click: () => {
            if (this.classNow == data.nodeKey) {
              this.classNow = -1
              this.deptId = ''
            } else {
              this.classNow = data.nodeKey
              this.deptId = data.id
            }
            this.pageno = 1
            this.$options.methods.getList(this)
          }
        }
      }, [
        h('span', data.title),
        h('span', {
          style: {
            float: 'right'
          }
        }, [
          h('span', {
            style: {
              marginRight: '40px'
            }
          }, data.leadName),
          h('span', data.userCount + '人')
        ])
      ])
    }
  },
  mounted() {
    // const url = '/bm/opera/sysuser/findSysuserPageList?pageNo=' + this.pageno + '&pageSize=' + this.pageSize
    this.$options.methods.getList(this)

    this.$axios.get('/bm/opera/role/findRoleList').then(res => {
      if (res.data.code == 200) {
        this.roleList = res.data.detail
      } else {
        this.$Message.error(res.data.description)
      }
    })

    this.$axios.get('/bm/opera/dept/findAllDeptTree').then(res => {
      if (res.data.code == 200) {
        this.deptData = formatTree(res.data.detail)
      } else {
        this.$Message.error(res.data.description)
      }
    }).catch(err => {
      this.$Message.error('网络错误，请稍后重试！')
    })
  }
}
function formatTree(subdata) {
  let arr = [];
  subdata.forEach((item, index) => {
    let subarr = {};
    subarr = {
      title: item.deptName,
      id: item.id,
      userCount: item.userCount,
      pid: item.pid,
      level: item.level,
      leadName: item.leadName,
      leadId: item.leadId,
      userCount: item.userCount,
      expand: true
    };

    if (item.sonDeptList.length > 0) {
      subarr.children = formatTree(item.sonDeptList);
    }

    arr.push(subarr);
  });

  return arr;
}
</script>

<style>
.selectttt {
  background: #2d8bf048;
}
</style>
